package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessHistoryMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.MediaProcessHistory;
import com.xuecheng.media.service.MediaFileService;
import com.xuecheng.media.service.MediaProcessService;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
@Slf4j
public class MediaProcessServiceImpl implements MediaProcessService {

    @Autowired
    private MediaProcessMapper mediaProcessMapper;
    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    @Autowired
    private MediaProcessHistoryMapper mediaProcessHistoryMapper;

    /**
     * 上传完文件要加入process
     * @param mediaProcess
     */
    @Override
    public void saveTask(MediaProcess mediaProcess) {
        mediaProcessMapper.insert(mediaProcess);
    }

    /**
     * 找处理任务
     * @param shardIndex
     * @param shardTotal
     * @param processors
     * @return
     */
    @Override
    public List<MediaProcess> findTasks(int shardIndex, int shardTotal, int processors) {

        return mediaProcessMapper.findTasks(shardIndex,shardTotal,processors);
    }

    //将任务改为运行中
    @Override
    public Boolean updateStatusFroRun(MediaProcess mediaProcess) {
        String status = mediaProcess.getStatus();
        if(status.equals("4")){
            //已经在运行了
            return false;
        }
        mediaProcess.setStatus("4");
        mediaProcessMapper.updateById(mediaProcess);
        return true;
    }

    /**
     * 如果错误，更新process的fail_count
     * 将File表更新为新的url，删除process表，插入history表
     * @param taskId
     * @param status
     * @param fileId
     * @param url
     * @param result
     */
    @Override
    @Transactional
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String result) {
        //要更新的任务
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if(mediaProcess == null){
            return ;
        }
        if(status.equals("3")){
            //处理出错
            //变成错误状态
            mediaProcess.setStatus("3");
            mediaProcess.setFailCount(mediaProcess.getFailCount()+1);
            mediaProcess.setErrormsg(result);
            mediaProcessMapper.updateById(mediaProcess);
        }
        //将File表更新为新的url
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        mediaFiles.setUrl("/"+mediaFiles.getBucket()+"/"+url);
        mediaFilesMapper.updateById(mediaFiles);
        //删除process表，
        mediaProcessMapper.deleteById(mediaProcess);
        //插入history表
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess,mediaProcessHistory);
        mediaProcessHistory.setFinishDate(LocalDateTime.now());
        mediaProcessHistoryMapper.insert(mediaProcessHistory);
    }
}
